"""
@date:2021-4-8
"""
import json

import requests
from bs4 import BeautifulSoup


class Wangyiyun:
    """
    网易云类
    """

    def __init__(self):
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'}

    def search(self, kw, search_type):
        session = requests.session()
        if search_type == 1:
            headers = {'x-requested-with': 'XMLHttpRequest'}
            headers.update(self.headers)
            music_list_url = f'https://music.liuzhijin.cn/'
            data = {
                'input': kw,
                'filter': 'name',
                'type': 'netease',
                'page': 1
            }
            response = session.post(music_list_url, headers=headers, data=data, verify=False)
            if response.status_code == 200:
                songs = []
                song_datas = json.loads(response.text).get('data')
                for song_data in song_datas:
                    songs.append([song_data.get('title'), song_data.get('author'), song_data.get('url')])
                else:
                    return songs
        if search_type == 1000:
            music_list_url = f'https://music.163.com/playlist?id={kw}'
            response = session.get(music_list_url, headers=self.headers, verify=False)
            if response.status_code == 200:
                soup = BeautifulSoup(response.text, 'lxml')  #
                song_datas = soup.select('#song-list-pre-cache')[0].findAll('a')
                songs = []
                for song_data in song_datas:
                    song_id, song_name = song_data.attrs['href'].split('=')[1], song_data.string
                    songs.append([song_id, song_name])
                else:
                    return songs

    @staticmethod
    def download(url, path):
        pass

